"""
Backtesting API routes
"""

from fastapi import APIRouter, HTTPException, Query
from typing import Dict, List, Optional
from datetime import datetime

from app.services.strategy_engine import strategy_engine

router = APIRouter()


@router.post("/run")
async def run_backtest(
    symbol: str = Query(..., description="Trading symbol"),
    timeframe: str = Query(default="4h", description="Timeframe"),
    start_date: str = Query(..., description="Start date (YYYY-MM-DD)"),
    end_date: str = Query(..., description="End date (YYYY-MM-DD)"),
    initial_capital: float = Query(default=10000, gt=0),
    strategy_params: Optional[Dict] = None
):
    """Run backtest with custom parameters"""
    try:
        results = strategy_engine.backtest_strategy(
            symbol=symbol,
            timeframe=timeframe,
            start_date=start_date,
            end_date=end_date,
            initial_capital=initial_capital
        )
        
        return {
            "backtest_id": f"{symbol}_{datetime.now().strftime('%Y%m%d_%H%M%S')}",
            "parameters": {
                "symbol": symbol,
                "timeframe": timeframe,
                "start_date": start_date,
                "end_date": end_date,
                "initial_capital": initial_capital,
                "strategy_params": strategy_params
            },
            "results": results
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/results/{backtest_id}")
async def get_backtest_results(
    backtest_id: str
):
    """Get backtest results by ID"""
    # Placeholder for retrieving stored results
    return {
        "backtest_id": backtest_id,
        "status": "completed",
        "results": {
            "total_return": 15.2,
            "max_drawdown": 8.5,
            "sharpe_ratio": 1.34,
            "win_rate": 0.68,
            "total_trades": 45
        }
    }


@router.get("/compare")
async def compare_strategies(
    symbols: List[str] = Query(default=["BTC/USDT", "ETH/USDT"]),
    timeframes: List[str] = Query(default=["1h", "4h"]),
    start_date: str = Query(default="2024-01-01"),
    end_date: str = Query(default="2024-12-31")
):
    """Compare multiple strategies"""
    results = []
    
    for symbol in symbols:
        for timeframe in timeframes:
            try:
                backtest_result = strategy_engine.backtest_strategy(
                    symbol=symbol,
                    timeframe=timeframe,
                    start_date=start_date,
                    end_date=end_date
                )
                
                results.append({
                    "symbol": symbol,
                    "timeframe": timeframe,
                    "results": backtest_result
                })
                
            except Exception as e:
                results.append({
                    "symbol": symbol,
                    "timeframe": timeframe,
                    "error": str(e)
                })
    
    return {
        "comparison": results,
        "best_performer": max(results, key=lambda x: x.get('results', {}).get('total_return', 0))
    }


@router.get("/performance-metrics")
async def get_performance_metrics():
    """Get standard performance metrics definitions"""
    return {
        "total_return": "Total percentage return over the backtest period",
        "annualized_return": "Annualized return percentage",
        "max_drawdown": "Maximum peak-to-trough decline",
        "sharpe_ratio": "Risk-adjusted return measure",
        "sortino_ratio": "Downside risk-adjusted return",
        "win_rate": "Percentage of profitable trades",
        "profit_factor": "Gross profit divided by gross loss",
        "avg_win": "Average winning trade return",
        "avg_loss": "Average losing trade return",
        "largest_win": "Largest single trade gain",
        "largest_loss": "Largest single trade loss"
    }


@router.delete("/clear-cache")
async def clear_backtest_cache():
    """Clear backtest cache"""
    return {"message": "Backtest cache cleared successfully"}
